// Channel 通道 A/B
package models

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/BertoldVdb/go-ais"
)

// ShipTrack 船舶位置报信息
type ShipTrack struct {
	//Channel 通道 A/B
	Channel string `json:"channel"`

	//MMSI MMSI号码
	MMSI string `json:"mmsi"`

	//Lng 经度(Longitude)
	Lng float64 `json:"lng"`

	//Lat 纬度(Latitude)
	Lat float64 `json:"lat"`

	//Cog 对地航向 (Course Over Ground)
	Cog float64 `json:"cog"`

	//Sog 对地航速 (Speed Over Ground)
	Sog float64 `json:"sog"`

	//Heading 船艏向 (heading)  取值范围 0°- 360° 真北线与船首线之间的夹角
	Heading uint16 `json:"heading"`

	//Rot 转向率 (Rate of turn/ROT) (-127 ~ +127)
	Rot int16 `json:"rot"`

	//NavStatus 航行状态
	NavStatus uint8 `json:"navStatus"`

	//Timestamp 时间戳,基于 1970年1月1日0时的秒数
	Timestamp int64 `json:"timestamp"`

	//Time 时间
	Time string `json:"time"`
}

// ToGeoFeature
func ToShipTrack(r *ais.PositionReport) *ShipTrack {
	mmsi := strconv.Itoa(int(r.UserID))
	t := time.Now()

	return &ShipTrack{
		Channel:   "",
		MMSI:      mmsi,
		Lng:       float64(r.Longitude),
		Lat:       float64(r.Latitude),
		Cog:       float64(r.Cog),
		Sog:       float64(r.Sog),
		Heading:   r.TrueHeading,
		Rot:       r.RateOfTurn,
		NavStatus: r.NavigationalStatus,
		Timestamp: t.Unix(),
		Time:      t.Local().Format("15:04:05"),
	}
}

func (s *ShipTrack) FromMsg123(r *ais.PositionReport) *ShipTrack {
	if s == nil {
		s = &ShipTrack{}
	}
	mmsi := strconv.Itoa(int(r.UserID))
	t := time.Now()

	s.MMSI = mmsi
	s.Lng = float64(r.Longitude)
	s.Lat = float64(r.Latitude)
	s.Cog = float64(r.Cog)
	s.Sog = float64(r.Sog)
	s.Heading = r.TrueHeading
	s.Rot = r.RateOfTurn
	s.NavStatus = r.NavigationalStatus
	s.Timestamp = t.Unix()
	s.Time = t.Local().Format("15:04:05")
	return s
}

func (s *ShipTrack) FromMsg18(r *ais.StandardClassBPositionReport) *ShipTrack {
	if s == nil {
		s = &ShipTrack{}
	}
	mmsi := strconv.Itoa(int(r.UserID))
	t := time.Now()

	s.MMSI = mmsi
	s.Lng = float64(r.Longitude)
	s.Lat = float64(r.Latitude)
	s.Cog = float64(r.Cog)
	s.Sog = float64(r.Sog)
	s.Heading = r.TrueHeading
	s.Rot = -128      //不可用
	s.NavStatus = 255 //不可用
	s.Timestamp = t.Unix()
	s.Time = t.Local().Format("15:04:05")
	return s
}

func (s *ShipTrack) FromMsg19(r *ais.ExtendedClassBPositionReport) *ShipTrack {
	if s == nil {
		s = &ShipTrack{}
	}
	mmsi := strconv.Itoa(int(r.UserID))
	t := time.Now()
	s.MMSI = mmsi
	s.Lng = float64(r.Longitude)
	s.Lat = float64(r.Latitude)
	s.Cog = float64(r.Cog)
	s.Sog = float64(r.Sog)
	s.Heading = r.TrueHeading
	s.Rot = -128      //不可用
	s.NavStatus = 255 //不可用
	s.Timestamp = t.Unix()
	s.Time = t.Local().Format("15:04:05")
	return s
}

// AISLoss 船舶航迹AIS 信号丢失/超时 信息
type AISLoss struct {
	MMSI      string `json:"mmsi"`
	Timestamp int64  `json:"timestamp"`
}

// MarshalBinary 二进制序列化 用于 redis 发布
func (m AISLoss) MarshalBinary() ([]byte, error) {
	return json.Marshal(m)
}
